<template>
  <el-card class="account-container">
    <h1 :style="`font-size: var(--el-font-size-extra-large)`" style="font-size: 26px; color: #615f5f">菜品列表</h1>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
      <el-breadcrumb-item
      ><a href="/message">待处理消息</a></el-breadcrumb-item
      >
      <el-breadcrumb-item>菜品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br>

    <el-form :model="form" label-width="120px">
      <el-form-item label="菜品名">
        <el-input v-model="form.dishName" />
      </el-form-item>
      <el-form-item label="商家名">
        <el-input v-model="form.merchantName" />
      </el-form-item>
      <el-form-item label="价格上限">
        <el-input v-model="form.upPrice" />
      </el-form-item>
      <el-form-item label="价格下限">
        <el-input v-model="form.downPrice" />
      </el-form-item>
      <el-form-item label="只显示未处理">
        <el-switch v-model="form.delivery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchClick">查询</el-button>
        <el-button  @click="resetClick">重置</el-button>
      </el-form-item>
    </el-form>
    <el-divider content-position="left">查询结果</el-divider>

    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"

        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :selectable="selectable" />
      <el-table-column prop="id" label="ID" width="120" />
      <el-table-column prop="name" label="菜品名称" width="180" />
      <el-table-column prop="status" label="状态" width="180">
        <template #default="scope">
          <el-text class="mx-1" :hidden="!(getStatus(scope.$index)===1)" type="primary">未发布</el-text>
          <el-text class="mx-1" :hidden="!(getStatus(scope.$index)===2)" type="success">已发布</el-text>
          <el-text class="mx-1" :hidden="!(getStatus(scope.$index)===0)" type="warning">审核中</el-text>
        </template>
        <!-- 之后添加是否审核 -->
      </el-table-column>
      <el-table-column prop="merchantName" label="商家名称" width="180"/>
      <el-table-column prop="price" label="价格" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button
              link
              type="primary"
              size="large"
              @click.prevent="detail(scope.$index)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
    <el-pagination
                   :background=true
                   v-model:total="totalCount"
                   v-model:page-size="form.pageSize"
                   :small=false
                   :page-sizes="[5, 10, 20, 50]"
                   @size-change="handleSizeChange"
                   layout="sizes, prev, pager, next, jumper"
                   @current-change="changePageNumber" />
    </div>
    <div class="demo-pagination-block" style="margin-top: 20px">
      <el-button type="primary" @click="clickAdd">新增菜品...</el-button>
      <el-button type="danger" :disabled="delete_list.length === 0
" @click="clickDelete">删除已选</el-button>
    </div>

    <el-divider content-position="left">批量审核通过</el-divider>

    <el-button type="success" @click="clickPass">批量通过审核</el-button>

    <!--  消息对话框    -->

    <el-dialog v-model="dialogFormVisible" title="添加菜品">
      <el-form :model="addForm">
        <el-form-item label="菜品名" :label-width="formLabelWidth" @change="checkDish">
          <el-input v-model="addForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="选择商家" :label-width="formLabelWidth">
          <el-select v-model="addForm.merchantId" clearable placeholder="Select">
            <el-option
                v-for="item in merchantList"
                :key="item.id"
                :label="item.shopName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="addForm.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="addForm.description" autocomplete="off" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmClickAdd"
            :disabled= "addForm.name==='' || addForm.merchantId==='' ||
                         addForm.price==='' || addForm.price===null ||
                          addForm.description ==='' || !isRepeat">
          确认添加
        </el-button>
      </span>
      </template>
    </el-dialog>

  </el-card>

</template>

<script setup>
import store from "@/store";
import {onMounted, reactive, ref} from "vue";
import {remove, page, add, checkByName, dishPass} from "@/api/dish";
import router from "@/router";
import {getMerchantById, searchMerchants} from "@/api/merchant";
import {ElMessage} from "element-plus";
import {open_error, open_success} from "@/utils/common";

const tableData = ref([]); // table数据

const delete_list = ref([]); // 需要删除的id列表

const dialogFormVisible = ref(false); // 添加弹出框的显示与否

const formLabelWidth = '100px';

const isRepeat = ref(false);

const merchantList = ref([]);

// 查询表单
const form = reactive({
  dishName: "",
  merchantName: "",
  upPrice: "",
  categoryId: 0, // 默认存0
  downPrice: "",
  price: "",
  image: "",
  description: "",
  merchantId: "",
  createTime: "",
  updateTime: "",
  delivery: false,
  pageNum: 1,
  pageSize: 5,
  status: 0,
});

// 添加表单
const addForm = reactive({
  dishName: "",
  merchantName: "",
  upPrice: "",
  categoryId: 0, // 默认存0
  downPrice: "",
  price: "",
  image: "",
  description: "",
  merchantId: "",
  createTime: "",
  updateTime: "",
  delivery: false,
  pageNum: 1,
  pageSize: 5,
  status: 1, // 管理员添加status的时候默认设置为已审核
});

// 禁用一些行的选择，对于菜品而言，一旦发布就不能被删除
const selectable = (row, index) => {
  let flag = true;
  if(row.status === 2 || row.status === 3){
    flag = false;
  }
  return flag;
}



// 查询菜品

const checkDish = () => {
  checkByName(addForm).then((res) => {
    isRepeat.value = (res.data === null);
  });
}


// 批量通过审核
const clickPass = () => {
  const id_array = reactive([]);
  for(let item in delete_list.value) {
    id_array.push(delete_list.value[item].id);
  }
  dishPass(id_array).then((res) => {
    if(res.state === 0) {
      open_success("操作成功");
      myPage();
    } else {
      open_error(res.message);
    }
  })
}


// 进入详情页修改信息
const detail = (index) => {
  const item = reactive(tableData.value[index]);
  router.push({
    name: 'dishesDetail',
    params: {
      id: item.id,
    }});
}

const getStatus = (index) => {
  return tableData.value[index].status;
}

const confirmClickAdd = () => {
  dialogFormVisible.value = false;
  addForm.createTime = new Date().format("yyyy-MM-dd hh:mm:ss");
  addForm.updateTime = new Date().format("yyyy-MM-dd hh:mm:ss");
  add(addForm).then((res) => {
    myPage();
  });
}

const clickAdd = () => {
  checkDish();
  dialogFormVisible.value = true;
}

const tableRowClassName = ({row, rowIndex}) => {
    if (rowIndex % 4 === 0) {
      return 'warning-row';
    } else if (rowIndex % 4 === 2) {
      return 'success-row';
    }
    return '';
}

// 提示重名
const open4 = () => {
  ElMessage({
    showClose: true,
    message: '菜名重复',
    type: 'error',
  })
}


const handleSelectionChange = (selection) => {
  delete_list.value = selection;
}

const clickDelete = () => {
  const id_array = reactive([]);
  for(let item in delete_list.value) {
    id_array.push(delete_list.value[item].id);
  }
  remove(id_array).then(() => {
    myPage();
  });
}


const totalCount = ref(10);


const searchClick = () => {
  myPage();
};

const resetClick = () => {
  form.sex = null;
  form.pageNum = 1;
  form.dishName = "";
  form.merchantName = "";
  form.phone = "";
  form.pageSize = 5;
  myPage();
}

const changePageNumber = (pageNum) => {
  form.pageNum = pageNum;
  myPage();
}

onMounted(() => {
  searchMerchant(); // 搜索商家
});


const myPage = () => {
  page(form).then(async (res) => { // 非异步处理一下
    for (let item in res.data.list) {
      const itemForm = reactive({
        id: (res.data.list[item].merchantId),
      });
      await getMerchantById(itemForm).then((ans) => {
        if(ans.data != null) res.data.list[item].merchantName = ans.data.shopName;
      });
    }
    return res;
  }).then((res) => {
    tableData.value = res.data.list;
    totalCount.value = res.data.total;
  });
}


const searchMerchant = () => {
  searchMerchants().then((res) => {
    merchantList.value = res.data;
    console.log(merchantList.value);
    myPage();
  })
}


const handleSizeChange = () => {
  myPage();
}

</script>
<style scoped>
.course {
  font-weight: bold;
  display: inline-block;
}
.course li {
  line-height: 36px;
  color: #409eff;
  cursor: pointer;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.el-table >>> .warning-row {
  background: oldlace;
}
.el-table >>> .success-row {
  background: #f0f9eb;
}


.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
